/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-05-03 16:57:39
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-06 08:33:38
 */
import { Node } from "cc";
import { Proto } from "../../common/data/Proto";
import { RandUtil } from "../../common/util/RandUtil";
import { Util } from "../../common/util/Util";
import { ClientEvent } from "../event/ClientEvent";
import { Conn } from "../net/Conn";
import BaseModel from "./BaseModel";


export default class FoodModCls extends BaseModel {

    /** 单例 */
    private constructor() { super(); }
    /** 实例 */
    static readonly ins = new FoodModCls();

    /** 食物字典 id->IModFood */
    private _foodDic: { [id: number]: IModFood } = {}

    listenProto(): void {

        Conn.on(Proto.S2C_FOOD_UPDATE, data => {
            //食物加载
            let foods: IModFood[] = [];
            data.foods.forEach(food => {
                if (!this._foodDic[food.id]) {
                    let modFood = this._foodDic[food.id] = food as any as IModFood;
                    modFood.color = food.rgb ? Util.rgb2color(food.rgb - 1) : RandUtil.randColor();
                    foods.push(modFood);
                }
            })
            this.sendEvent(ClientEvent.FOOD_LOAD, foods);
        })

        Conn.on(Proto.S2C_FOOD_UNLOAD, data => {
            //食物卸载
            let foods: IModFood[] = [];
            data.foodIds.forEach(foodId => {
                let food = this._foodDic[foodId.id];
                if (food) {
                    food.eaterId = foodId.eaterId;
                    foods.push(food);
                    delete this._foodDic[foodId.id];
                }
            })
            this.sendEvent(ClientEvent.FOOD_UNLOAD, foods);
        })
    }

}
export const FoodMod = FoodModCls.ins;

export interface IModFood {
    /** 食物id */
    id: number
    /** 坐标x */
    x: number
    /** 坐标y */
    y: number
    /** 宽度 */
    w: number
    /** 颜色字符串 */
    color: string
    /** 场景中的节点 */
    node?: Node
    /** 吃了食物的蛇节点id */
    eaterId?: number
}
